package com.code.leetcode.before50;

/**
 * @author codeDorado
 * @version 1.0
 * @date 2020/7/25 9:47
 */
public class The79 {

    private boolean[][] marked;
    private int[][] direction = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
    int m, n;
    char[][] board;
    String word;

    public boolean exist(char[][] board, String word) {
        m = board.length;
        if (m < 1) return false;
        n = board[0].length;
        marked = new boolean[m][n];
        this.board = board;
        this.word = word;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (dfs(i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean dfs(int i, int j, int start) {
        if (start == word.length() - 1) {
            return board[i][j] == word.charAt(start);
        }

        if (board[i][j] == word.charAt(start)) {
            marked[i][j] = true;
            for (int k = 0; k < 4; k++) {
                int X = i + direction[k][0];
                int Y = j + direction[k][1];
                if (isArea(X, Y) && !marked[X][Y]) {
                    if (dfs(X, Y, start + 1)){
                        return true;
                    }
                }
            }
            marked[i][j] = false;
        }
        return false;
    }

    private boolean isArea(int x, int y) {
        return x >= 0 && x < m && y >= 0 && y < n;
    }


}
